"""
插件管理模型
"""
from apps.extensions import db
from datetime import datetime
import json


class SysPlugin(db.Model):
    """插件管理表"""
    __tablename__ = 'sys_plugin'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
    name = db.Column(db.String(100), nullable=False, comment='插件名称')
    version = db.Column(db.String(20), nullable=False, comment='插件版本')
    description = db.Column(db.Text, comment='插件描述')
    author = db.Column(db.String(100), comment='插件作者')
    
    # 状态相关
    status = db.Column(db.Integer, default=1, comment='状态：0-禁用，1-启用')
    is_installed = db.Column(db.Boolean, default=False, comment='是否已安装')
    is_enabled = db.Column(db.Boolean, default=False, comment='是否已启用')
    
    # 文件信息
    file_size = db.Column(db.BigInteger, comment='文件大小(字节)')
    file_hash = db.Column(db.String(64), comment='文件哈希值')
    
    # 时间信息
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    installed_at = db.Column(db.DateTime,default=datetime.now, comment='安装时间')
    enabled_at = db.Column(db.DateTime, comment='启用时间')
    
    # 扩展信息（JSON格式）
    extra_info = db.Column(db.Text, comment='扩展信息(JSON格式)')
    
    # 排序
    sort_order = db.Column(db.Integer, default=0, comment='排序')
    
    def __repr__(self):
        return f'<SysPlugin {self.name}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'version': self.version,
            'description': self.description,
            'author': self.author,
            'status': self.status,
            'is_installed': self.is_installed,
            'is_enabled': self.is_enabled,
            'file_size': self.file_size,
            'file_hash': self.file_hash,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
            'installed_at': self.installed_at.strftime('%Y-%m-%d %H:%M:%S') if self.installed_at else None,
            'enabled_at': self.enabled_at.strftime('%Y-%m-%d %H:%M:%S') if self.enabled_at else None,
            'extra_info': self.get_extra_info(),
            'sort_order': self.sort_order
        }
    
    def get_extra_info(self):
        """获取扩展信息"""
        if self.extra_info:
            try:
                return json.loads(self.extra_info)
            except:
                return {}
        return {}
    
    def set_extra_info(self, info_dict):
        """设置扩展信息"""
        self.extra_info = json.dumps(info_dict, ensure_ascii=False)
    
    def get_status_text(self):
        """获取状态文本"""
        if not self.is_installed:
            return '未安装'
        elif not self.is_enabled:
            return '已安装'
        else:
            return '已启用'
    
    def get_status_class(self):
        """获取状态CSS类"""
        if not self.is_installed:
            return 'layui-bg-gray'
        elif not self.is_enabled:
            return 'layui-bg-orange'
        else:
            return 'layui-bg-green'
    
    def get_file_size_text(self):
        """获取文件大小文本"""
        if not self.file_size:
            return '未知'
        
        size = self.file_size
        if size < 1024:
            return f"{size} B"
        elif size < 1024 * 1024:
            return f"{size / 1024:.1f} KB"
        elif size < 1024 * 1024 * 1024:
            return f"{size / 1024 / 1024:.1f} MB"
        else:
            return f"{size / 1024 / 1024 / 1024:.1f} GB"


class SysPluginLog(db.Model):
    """插件操作日志表"""
    __tablename__ = 'sys_plugin_log'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
    plugin_id = db.Column(db.Integer, db.ForeignKey('sys_plugin.id'), comment='插件ID')
    operation = db.Column(db.String(50), nullable=False, comment='操作类型')
    operation_desc = db.Column(db.String(500), comment='操作描述')
    operator = db.Column(db.String(100), comment='操作人')
    ip_address = db.Column(db.String(50), comment='IP地址')
    user_agent = db.Column(db.String(500), comment='用户代理')
    
    # 操作结果
    success = db.Column(db.Boolean, default=True, comment='是否成功')
    error_message = db.Column(db.Text, comment='错误信息')
    
    # 时间信息
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    
    # 关联关系
    plugin = db.relationship('SysPlugin', backref=db.backref('logs', lazy='dynamic'))
    
    def __repr__(self):
        return f'<SysPluginLog {self.operation} {self.plugin_id}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'plugin_id': self.plugin_id,
            'plugin_name': self.plugin.name if self.plugin else None,
            'operation': self.operation,
            'operation_desc': self.operation_desc,
            'operator': self.operator,
            'ip_address': self.ip_address,
            'user_agent': self.user_agent,
            'success': self.success,
            'error_message': self.error_message,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None
        } 